package com.newgoldcurrency.utils.network;

import androidx.annotation.NonNull;

import com.google.gson.JsonParser;
import com.newgoldcurrency.App;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class ResponseContentInterceptor implements Interceptor {
    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        int retryNum = 0;
        Request request = chain.request();
        Response response = chain.proceed(request);
        String data = response.body().string();
        String message = JsonParser.parseString(data).getAsJsonObject().get("message").getAsString();
        while (!App.sp.getString("token", "").equals("") && (message.equals("Please login first") || message.equals("System internal error")) && retryNum++ <= 5) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                response.close();
                response = chain.proceed(request);
                data = response.body().string();
                message = JsonParser.parseString(data).getAsJsonObject().get("message").getAsString();
            }
        }
        return response.newBuilder().body(ResponseBody.create(response.body().contentType(), data)).build();
    }
}
